/**************************************************************************
 * @doc CPAC
 * @module CPACSTL.C |
 * Source code for the CPAC settlement functions.
 *
 * Product         :   SoftPay 2000 (Global Payment Methodology).
 * <nl>Developer   :   SoftPay Development Team (I_SP2000).
 * <nl>Notes       :
 *
 * @head3 CPAC Functions |
 * @index | CPAC
 * @end
 *
 * Copyright (c) 1996-2000 by VeriFone Inc. All rights reserved.
 *
 * No part of this software may be used, stored, compiled, reproduced,
 * modified, transcribed, translated, transmitted, or transferred, in any form
 * or by any means whether electronic, mechanical, magnetic, optical,
 * or otherwise, without the express prior written permission of VeriFone, Inc.
 *
 * Revision History
 * ------------------------------------------------------------------------
$Log: /SoftPay/SPK2SIM/Source/CPACSrc/cpacstl.c $
 * ------------------------------------------------------------------------
 ********************************************************************************/
#include <project.h>
#define CPACSTL_C

#include <aclconio.h>
#include <stdio.h>
#include <stdlib.h>
#include <acldev.h>
#include <aclstr.h>
#include <aclutil.h>
#include <ascii.h>
#include <amexhost.h>
#include <svctxo.h>
#include <iso8583.h>
#include <message.h>
#include <xmodem.h>
#include <errno.h>
#include <define.h>
#include <transact.h>
#include <protocol.h>
#include <packet.h>
#include <format.h>
#include <multilng.h> //citiphil_don_DSC_1.4

#include <tran.h>
#include <comm.h>
#include <modem.h>
#include <ppt.h>
#include <pipmsg.h>
#include <menufunc.h>
#include <msg.h>
#include <msgfuncs.h>
#include <bdt.h>
#include <mht.h>
#include <hdt.h>
#include <accum.h>
#include <form.h>
#include <date.h>
#include <mem.h>
#include <spdebug.h>
#include <isoutl.h>
#include <piputl.h>
#include <isoload.h>
#include <ifldtbl.h>
#include <isoutl.h>
#include <init.h>
#include <mit.h>
#include <entry.h>
#include <logo.h>
#include <string.h>
#include <aclfile.h>
#include <confio.h>
#include <pwrfids.h>
#include <oper.h>
#include <menus.h>
#include <funcids.h>
#include <tblutil.h>
#include "cpacsize.h"
#include "cpacids.h"

#include "cpacsrc.h"
#include "cpacbat.h"
#include "cpacmsg.h"
#include "cpacoper.h"
#include "cpatran.h"
#include "cpacprnt.h"
#include "cpac.h"
#include "cpacstl.h"
#include "cpacextn.h"
#include "sqautils.h" //citiphil_vipin_DSC_don

#include "..\imamsrc\ImamUtil.h"
#include "..\imamsrc\imamsrc.h"

#ifdef VXEMVAPP //Added by Thiru : To cater for TC Resend during settlement
#include "..\EMVSrc\EMVids.h"
#include "..\EMVSrc\EMVsrcdef.h"
#include "..\EMVSrc\EMViso.h"
#include "..\EMVSrc\EMVprnt.h"
#include "..\EMVSrc\emvmsg.h"
#include "..\EMVSrc\EMVTC.h"
#endif

#ifdef ICICI
	#include "..\ICICsrc\ICICids.h"
#endif  /*  ICICI  */

#define SIZE_CPAC_REC        REC_SIZEOF(CPAC_REC)
//#define CPAC_AUTO_SETTLE_LOOK_UP_TIME   30  // check for AS every 2 mints.

static int inChangeAutoSetlDate(int inHostNum);
extern HOST_8583_DATA* psrCreateHostData(void);  // CPAC_LINT added
extern int inCPACBaseRespValidation(VALIDATION_STRUCT* psrRespValStruct,int  inInternalVal);
void vdMustSettleHostFlags(VS_BOOL fSettleFlag);
int inResetDemoBatch(TRANSACTION_OBJECT* pobTran);

extern int inCloseSDLC(int h_modem,int bps);
//extern int inAXAPCreateVariantStruct63(void); //Praveen_s1 14042005 //LIEM DISABLE
extern int inGlobalMerchantHandle;
extern int inGlobalAutoHandle;

/* Saritha_b1................Start...Fix for Batch Upload Processing Code */

#ifdef PROC_CODE_CHNG  /* Saritha_b1 changed from TLFB to PROC_CODE_CHNG*/

//extern void vdGetSCBKProcCode (BATCH_REC *psrBRec, unsigned char * pszData);
//extern void vdSCBKBatRec2GDS (BATCH_REC *psrBRec);

void vdCPACPCChngBatRec2GDS(BATCH_REC* psrBRec);
void vdGetCPACPCChng(BATCH_REC* psrBRec,unsigned char* pszData);
#endif /*PROC_CODE_CHNG*/

#ifdef ICICI
extern int inSendReceiveHDFC (PROTOCOL_OBJECT *pobProtocol, PACKET_OBJECT *pobPacket);
#endif  /* ICICI  */

/* Saritha_b1................End...Fix for Batch Upload Processing Code */

/*********************************************************************************************
* @func int | inCPACSendDetailRecords |
* This function will do a detail record upload to the host.
* (Send the batch records one by one as a 0320 message
* request packet).  At the end of Detail Records upload this
* function will call an other function inReconcile to
* send the totals again.
*
* @parm TRANSACTION_OBJECT * | pobTran |
*       This is the transaction object.
*
* @rdesc Returns inRetVal returned by inFinalCPACRecon() if all goes well.
* @flag int | VS_ERR
* @end
**********************************************************************************************/

int inCPACSendDetailRecords(TRANSACTION_OBJECT* pobTran) {
    int inRetVal;
    short shTranCode;
    int inLoop = VS_SUCCESS;
    short shPIPTransCode;
    long lnSTAN;
    char szMessage[RESP_MSG_SIZE + 1];
    long lnDBWhat = DB_FIRST;

    /* Saritha_b1................Start...Fix for Batch Upload Processing Code */
#ifdef PROC_CODE_CHNG       //Saritha_b1 changed from TLFB to PROC_CODE_CHNG

    int inTranCnt = 0;
    int inCnt = 0;

#endif  /*PROC_CODE_CHNG */

    /* Saritha_b1................End...Fix for Batch Upload Processing Code */

    /** /pdebug(("--inSendDetailRecords--"));*/


    lnSTAN = pobTran->srBRec.lnSTAN;

    if (inCPACCreateVariantStruct60() == VS_ERR) {
        vdFree((char *) psrVariant60);
        vdSGErrorMessage(NO_MEM_ERR_MSG);
        return(VS_ERR);
    }


    if (inCPACCreateVariantStruct63() == VS_ERR) {
        vdFreeVariantTables();
        vdSGErrorMessage(NO_MEM_ERR_MSG);
        return(VS_ERR);
    }


    if ((psrHostData = psrCreateHostData()) == (HOST_8583_DATA *) NULL_CH) {
        vdFreeHostData(psrHostData);
        vdFreeVariantTables();
        vdSGErrorMessage(NO_MEM_ERR_MSG);
        return (VS_ERR);
    }


    if ((psrHostData->c8583_data = psrCreateCommData(pobTran, CPAC_SEND_SIZE, VS_FALSE)) == (COMM_8583_DATA *) NULL_CH) {
        vdSGErrorMessage(NO_MEM_ERR_MSG);
        vdFreeISO8583Data(psrHostData);
        return (VS_ERR);
    }

	psrHostData->c8583_data->transceiver = inImamTxRx8583;  //
#ifdef MODEM
	if (inGetUCLCommLink()==0) {  // to get resp timeout
		MODEM_OBJECT *obModem;
		obModem = (MODEM_OBJECT *)obCommunication.Data;
		psrHostData->c8583_data->comm_timeout         = obModem->shGetRespTimeOut(obModem->srCPT);  // for Response TimeOut
		psrHostData->c8583_data->wait_for_carrier     = obModem->shGetCarrierTimeOut(obModem->srCPT); // for Carier TimeOut
	}
#endif

    ((VALIDATION_STRUCT *) (psrHostData->c8583_data->v_parms))->comm_struct = psrHostData->c8583_data;

    /** Added fix for duplicate Advice **/
    psrHostData->c8583_data->validation = (PFI_PVOID_INT) inCPACBaseRespValidation; //dup_adv


    /* Disable reversal handling while doing close processing */
    psrHostData->reverse_flag = 0;
    psrHostData->c8583_data->validation = (PFI_PVOID_INT) inBaseValidationLow;



    /* Get the total number of records in the batch */
    if (inGetHostTranCnt(pobTran) <= 0) /* added for single batch */ {
        vdSGErrorMessage(BATCH_EMPTY_MSG);
        vdFreeISO8583Data(psrHostData);
        return(VS_ERR);
    }


    /** /pdebug (("inTotRecords = %d", inTotRecs));*/

    vdDisplayMessageFromFile(UPLOADING_BATCH_MSG15, STATUS_MSG);


    /*  Saritha_b1 ................Start..Fix for Batch Upload Processing Code*/
#ifdef PROC_CODE_CHNG       //Saritha_b1 changed from TLFB to PROC_CODE_CHNG



    inTranCnt = inGetHostTranCnt(pobTran);
    pobTran->srBKey.inBatchHostIndex = inGetBatchIndex();
    lnDBWhat = DB_LAST;
    if (strcmp(szGetHostName(), "AXAP") != 0)
        do {
            if ((inRetVal = inLoadNextBatchRec(pobTran, lnDBWhat)) == VS_SUCCESS) {
                if (pobTran->srBKey.fVoided) {
                    --inTranCnt;
                    lnDBWhat = DB_PREVIOUS;
                } else
                    break;
            } else
                inRetVal = VS_ERR;
        } while (inRetVal == VS_SUCCESS);
    lnDBWhat = DB_FIRST;

#endif  /*PROC_CODE_CHNG */
    /* Saritha_b1....................End..Fix for Batch Upload Processing Code*/

    /* Get the batch records one by one for this host and upload
        the batch records to the host */

    do {

        memset(&srISO, 0, sizeof(ISO_DATA));

        // pobTran->srBKey.inBatchHostIndex = inGetHostHandle ();
        pobTran->srBKey.inBatchHostIndex = inGetBatchIndex();

        if ((inRetVal = inLoadNextBatchRec(pobTran, lnDBWhat)) == VS_SUCCESS) {

            lnDBWhat = DB_NEXT;

#ifdef CITI_IND
            /*          This is only used if you don't want voided transaction to be sent during
                        BATCH UPLOAD. */
            if (pobTran->srBKey.fVoided) {
                if (strcmp(szGetHostName(), "AXAP") != 0)
                    continue;
            }
#endif /*CITI_IND*/


#ifdef CITI_SING  //KiaSoon 060206: Do not send void txn for batch upload
            /*          This is only used if you don't want voided transaction to be sent during
                        BATCH UPLOAD. */
            if (pobTran->srBKey.fVoided) {
                if (strcmp(szGetHostName(), "AXAP") != 0)
                    continue;
            }
#endif /*CITI_SING*/

#ifdef PROC_CODE_CHNG       //Saritha_b1 changed from TLFB to PROC_CODE_CHNG

            /*  Saritha_b1................Start...Fix for Batch Upload Processing Code*/

            inCnt++;

            /*  Saritha_b1................End...Fix for Batch Upload Processing Code*/

#endif /* PROC_CODE_CHNG */

#ifdef TLFB

            /*          This is only used if you don't want voided transaction to be sent during
                        BATCH UPLOAD. */
            if (pobTran->srBKey.fVoided) {
                if (strcmp(szGetHostName(), "AXAP") != 0)
                    continue;
            }
#endif /*CITI_IND*/


            vdCPACBatRec2GDS(&pobTran->srBRec);

            /*          Do not send void of untrickle fed transaction  */
            // CPAC_UNBKL added
            if ((pobTran->srBKey.fVoided) && (pobTran->srBKey.fUploaded != VS_TRUE)) {
                if (strcmp(szGetHostName(), "AXAP") != 0)
                    continue;
            }

            if  (pobTran->srBKey.fVoided && !fGetImamSendVoided()) { //LIEM : do not send voided transaction
				LOG_PRINTFF((0x08L, "VOIDED TRX. NOT SEND!"));
				continue;
            }

/* Saritha_b1................Start...Fix for Batch Upload for Processing Code */
#ifdef PROC_CODE_CHNG       //Saritha_b1 changed from TLFB to PROC_CODE_CHNG

	       // if ((inCnt == inTranCnt))
	    //            vdCPACPCChngBatRec2GDS(&pobTran->srBRec);

#endif  /*PROC_CODE_CHNG */
            /* Saritha_b1................End...Fix for Batch Upload for Processing Code */

            vdSGCode(BATCH_UPLOAD);
            shTranCode = inGGCode();
            inStoreTranFlexiData(pobTran, AMEX_PIP_TRANS_CODE, (unsigned char *) &shTranCode, 2);


            if ((shPIPTransCode = shLoadPIPTransCode(shTranCode)) == VS_ERR) {
                inLoop = VS_ERR;
                break;
            }


            /** /pdebug (("inGetCDTHostIndex = %d", inGetCDTHostIndex()));*/
            if (inIncSTAN() == VS_SUCCESS) {
                pobTran->srBRec.lnSTAN = lnGetSTAN();
                /* Reload Trace Nbr. */


                vdInitializeValidationStruct(pobTran, psrHostData->c8583_data->v_parms);

                if ((inRetVal = pip_trans((int) shPIPTransCode, psrHostData)) != PIP_APPROVAL) {

                    /*pdebug(("inRetVal=%d errno=%d", inRetVal, errno));*/
                    if ((strlen((char *) srISO.pszField44) > 0) && (strncmp((char *) srISO.pszField44, "00", 2))) {

                        vdGetMessageFromThisFile(PIP_MESSAGE_FILE, DCP_APPROVAL_MSG, szMessage);
                        vdSGRespMsg(szMessage);
                    } else if (strncmp((char *) srISO.pszField39, "00", 2)) {

                        /*
                                 *      Do Not Overwrite previously set error messages.
                                 */
                        if (lnGGErrorMessage() == 0L) {

                            /*                            vdGetMessageFromFile( AMEX_ERROR_MSG, szMessage);
                                                        strcat(szMessage, (char *)srISO.pszField39);
                                                        vdSGRespMsg(szMessage);
                            */
                            vdCPACDispRespMsg(pobTran);  //CPAC_UNBKL added after MK
                        }

                    }
					{ //LIEM : Add checking if batch upload advice ignored or not
						if ((fGetImamForceSettle()) && (inRetVal == HOST_ERROR) && (strncmp((char *)srISO.pszField39, "00", 2))) {
							LOG_PRINTFF((0x08L, "BATCH UPLOAD ADVICE, THERE IS A RESPONSE", (char *)srISO.pszField39)); 
							LOG_PRINTFF((0x08L, "BATCH UPLOAD ADVICE, RESULT IGNORED, RESP CODE [%s]", (char *)srISO.pszField39)); 
						} else {
							LOG_PRINTFF((0x08L, "BATCH UPLOAD ADVICE RESULT CHECKED, RESP CODE [%s]", (char *)srISO.pszField39)); 
							vdSGErrorMessage(UPLOAD_FAIL_ERR_MSG21);
							inLoop = VS_ERR;
						}
					}//end of add
                    //vdSGErrorMessage(UPLOAD_FAIL_ERR_MSG21);  // : Original
                    //inLoop = VS_ERR;
                }

            } else
                inLoop = VS_ERR;

		} else if (inRetVal == VS_EOB)
            break;
        else {

            vdSGErrorMessage(REC_GET_ERR_MSG21);
            inLoop = (VS_ERR);
        }
        /** /pdebug (("inCurRec = %d", inCurRec));*/
        /** /pdebug (("inLoop = %d", inLoop));*/
    } while (inLoop == VS_SUCCESS);

    vdFreeISO8583Data(psrHostData);

    /* Send the totals to the host again */
    if (inLoop == VS_SUCCESS) {

        if (inIncSTAN() != VS_SUCCESS)
            inRetVal = VS_ERR;
        else {

            pobTran->srBRec.lnSTAN = lnGetSTAN();
            pobTran->srBKey.lnOrgSTAN = lnSTAN;
            inIncInvNum();  // CPAC_UNBKL added  CPAC_?
            inRetVal = inFinalCPACRecon(pobTran);
        }
    } else
    {

        inRetVal = VS_ERR;
    	}


    return(inRetVal);
}

int inImamSendAllTC(TRANSACTION_OBJECT* pobTran) 
{
    int inRetVal;
    short shTranCode;
    int inLoop = VS_SUCCESS;
    short shPIPTransCode;
    long lnSTAN;
    char szMessage[RESP_MSG_SIZE + 1];
    long lnDBWhat = DB_FIRST;

	short inImamCode;
	short inImamTransactionCode;
	short ImamTransactionCode;

    /* Saritha_b1................Start...Fix for Batch Upload Processing Code */
#ifdef PROC_CODE_CHNG       //Saritha_b1 changed from TLFB to PROC_CODE_CHNG
    int inTranCnt = 0;
    int inCnt = 0;
#endif  /*PROC_CODE_CHNG */
    /* Saritha_b1................End...Fix for Batch Upload Processing Code */

    lnSTAN = pobTran->srBRec.lnSTAN;
    if (inCPACCreateVariantStruct60() == VS_ERR) {
        vdFree((char *) psrVariant60);
        vdSGErrorMessage(NO_MEM_ERR_MSG);
        return(VS_ERR);
    }
    if (inCPACCreateVariantStruct63() == VS_ERR) {
        vdFreeVariantTables();
        vdSGErrorMessage(NO_MEM_ERR_MSG);
        return(VS_ERR);
    }
    if ((psrHostData = psrCreateHostData()) == (HOST_8583_DATA *) NULL_CH) {
        vdFreeHostData(psrHostData);
        vdFreeVariantTables();
        vdSGErrorMessage(NO_MEM_ERR_MSG);
        return (VS_ERR);
    }
    if ((psrHostData->c8583_data = psrCreateCommData(pobTran, CPAC_SEND_SIZE, VS_FALSE)) == (COMM_8583_DATA *) NULL_CH) {
        vdSGErrorMessage(NO_MEM_ERR_MSG);
        vdFreeISO8583Data(psrHostData);
        return (VS_ERR);
    }
	psrHostData->c8583_data->transceiver = inImamTxRx8583;  //
#ifdef MODEM
	if (inGetUCLCommLink()==0) {  // to get resp timeout
		MODEM_OBJECT *obModem;
		obModem = (MODEM_OBJECT *)obCommunication.Data;
		psrHostData->c8583_data->comm_timeout         = obModem->shGetRespTimeOut(obModem->srCPT);  // for Response TimeOut
		psrHostData->c8583_data->wait_for_carrier     = obModem->shGetCarrierTimeOut(obModem->srCPT); // for Carier TimeOut
	}
#endif
    ((VALIDATION_STRUCT *) (psrHostData->c8583_data->v_parms))->comm_struct = psrHostData->c8583_data;
    /** Added fix for duplicate Advice **/
    psrHostData->c8583_data->validation = (PFI_PVOID_INT) inCPACBaseRespValidation; //dup_adv
    /* Disable reversal handling while doing close processing */
    psrHostData->reverse_flag = 0;
    psrHostData->c8583_data->validation = (PFI_PVOID_INT) inBaseValidationLow;

    /* Get the total number of records in the batch */
    if (inGetHostTranCnt(pobTran) <= 0) /* added for single batch */ {
        vdSGErrorMessage(BATCH_EMPTY_MSG);
        vdFreeISO8583Data(psrHostData);
        //return(VS_ERR);
		return(VS_SUCCESS);
    }
	DisplayStatus("UPLOAD ALL TC...");
    //vdDisplayMessageFromFile(UPLOADING_BATCH_MSG15, STATUS_MSG);

    /*  Saritha_b1 ................Start..Fix for Batch Upload Processing Code*/
#ifdef PROC_CODE_CHNG       //Saritha_b1 changed from TLFB to PROC_CODE_CHNG
    inTranCnt = inGetHostTranCnt(pobTran);
    pobTran->srBKey.inBatchHostIndex = inGetBatchIndex();
    lnDBWhat = DB_LAST;
    if (strcmp(szGetHostName(), "AXAP") != 0) {
        do {
            if ((inRetVal = inLoadNextBatchRec(pobTran, lnDBWhat)) == VS_SUCCESS) {
                if (pobTran->srBKey.fVoided) {
                    --inTranCnt;
                    lnDBWhat = DB_PREVIOUS;
                } else {
                    break;
				}
            } else {
                inRetVal = VS_ERR;
			}
        } while (inRetVal == VS_SUCCESS);
	}
    lnDBWhat = DB_FIRST;
#endif  /*PROC_CODE_CHNG */
    /* Saritha_b1....................End..Fix for Batch Upload Processing Code*/

    /* Get the batch records one by one for this host and upload the batch records to the host */
    do {
        memset(&srISO, 0, sizeof(ISO_DATA));
        // pobTran->srBKey.inBatchHostIndex = inGetHostHandle ();
        pobTran->srBKey.inBatchHostIndex = inGetBatchIndex();
        if ((inRetVal = inLoadNextBatchRec(pobTran, lnDBWhat)) == VS_SUCCESS) {
            lnDBWhat = DB_NEXT;
#ifdef CITI_SING  //KiaSoon 060206: Do not send void txn for batch upload
            /* This is only used if you don't want voided transaction to be sent durin BATCH UPLOAD. */
            if (pobTran->srBKey.fVoided) {
                if (strcmp(szGetHostName(), "AXAP") != 0)
                    continue;
            }
#endif /*CITI_SING*/

#ifdef PROC_CODE_CHNG       //Saritha_b1 changed from TLFB to PROC_CODE_CHNG
            /*  Saritha_b1................Start...Fix for Batch Upload Processing Code*/
            inCnt++;
            /*  Saritha_b1................End...Fix for Batch Upload Processing Code*/
#endif /* PROC_CODE_CHNG */
			{	
				inImamCode = pobTran->srBRec.inCode;
				inImamTransactionCode = pobTran->inTransactionCode;
				ImamTransactionCode = pobTran->srTRTRec.TransactionCode;
			}
            vdCPACBatRec2GDS(&pobTran->srBRec);
            /*          Do not send void of untrickle fed transaction  */
            // CPAC_UNBKL added
            if ((pobTran->srBKey.fVoided) && (pobTran->srBKey.fUploaded != VS_TRUE)) {
                if (strcmp(szGetHostName(), "AXAP") != 0)
                    continue;
            }
            if  (pobTran->srBKey.fVoided && !fGetImamSendVoided()) { //LIEM : do not send voided transaction
				LOG_PRINTFF((0x08L, "VOIDED TRX. NOT SEND!"));
				continue;
            }
			{ //LIEM
				char buff[20];
				memset(buff, 0x00, sizeof(buff));
				vdGetTCFlag(&pobTran->srBRec, (unsigned char *)buff);
				LOG_PRINTFF((0x08L, "TC [%s|%ld]", buff, (long)&pobTran->srBRec));
				if (strcmp(buff, "1")){
					LOG_PRINTFF((0x08L, "NO MORE TC...NEXT/SKIP"));
					continue;
				}
			}
			{//return it to original one 
				pobTran->srBRec.inCode = TC_UPLOAD;
				pobTran->inTransactionCode = TC_UPLOAD;
				pobTran->srTRTRec.TransactionCode = TC_UPLOAD;
			}
			shTranCode = TC_UPLOAD;
            inStoreTranFlexiData(pobTran, AMEX_PIP_TRANS_CODE, (unsigned char *) &shTranCode, 2);

            if ((shPIPTransCode = shLoadPIPTransCode(shTranCode)) == VS_ERR) {
                inLoop = VS_ERR;
                break;
            }

            if (inIncSTAN() == VS_SUCCESS) {
                pobTran->srBRec.lnSTAN = lnGetSTAN();
                /* Reload Trace Nbr. */
                vdInitializeValidationStruct(pobTran, psrHostData->c8583_data->v_parms);
                if ((inRetVal = pip_trans((int) shPIPTransCode, psrHostData)) != PIP_APPROVAL) {
                    /*pdebug(("inRetVal=%d errno=%d", inRetVal, errno));*/
                    if ((strlen((char *) srISO.pszField44) > 0) && (strncmp((char *) srISO.pszField44, "00", 2))) {
                        vdGetMessageFromThisFile(PIP_MESSAGE_FILE, DCP_APPROVAL_MSG, szMessage);
                        vdSGRespMsg(szMessage);
                    } else if (strncmp((char *) srISO.pszField39, "00", 2)) {
                        // Do Not Overwrite previously set error messages.
                        if (lnGGErrorMessage() == 0L) {
                            vdCPACDispRespMsg(pobTran);  //CPAC_UNBKL added after MK
                        }
                    }
					{ //LIEM : Add checking if batch upload advice ignored or not
						if ((fGetImamForceSettle()) && (inRetVal == HOST_ERROR) && (strncmp((char *)srISO.pszField39, "00", 2))) {
							LOG_PRINTFF((0x08L, "BATCH UPLOAD ADVICE, THERE IS A RESPONSE", (char *)srISO.pszField39)); 
							LOG_PRINTFF((0x08L, "BATCH UPLOAD ADVICE, RESULT IGNORED, RESP CODE [%s]", (char *)srISO.pszField39)); 
						} else {
							LOG_PRINTFF((0x08L, "BATCH UPLOAD ADVICE RESULT CHECKED, RESP CODE [%s]", (char *)srISO.pszField39)); 
							vdSGErrorMessage(UPLOAD_FAIL_ERR_MSG21);
							inLoop = VS_ERR;
						}
					}//end of add
                    //vdSGErrorMessage(UPLOAD_FAIL_ERR_MSG21);  // : Original
                    //inLoop = VS_ERR;
                } else {
					//LIEM
					char buff[20];
					memset(buff, 0x00, sizeof(buff));
					vdSetTCFlag(&pobTran->srBRec, (unsigned char *)buff);
					{	
						pobTran->srBRec.inCode = inImamCode;
						pobTran->inTransactionCode = inImamTransactionCode;
						pobTran->srTRTRec.TransactionCode = ImamTransactionCode;
					}
					inImamModifyCurrentBatchRec(pobTran);
				}
            } else {
                inLoop = VS_ERR;
			}
		} else if (inRetVal == VS_EOB) {
            break;
        } else {
            vdSGErrorMessage(REC_GET_ERR_MSG21);
            inLoop = (VS_ERR);
        }
        /** /pdebug (("inCurRec = %d", inCurRec));*/
        /** /pdebug (("inLoop = %d", inLoop));*/
    } while (inLoop == VS_SUCCESS);

    vdFreeISO8583Data(psrHostData);
    if (inLoop == VS_SUCCESS) {
        inIncSTAN();
        pobTran->srBRec.lnSTAN = lnGetSTAN();
        pobTran->srBKey.lnOrgSTAN = lnSTAN;
        inIncInvNum();  // CPAC_UNBKL added  CPAC_?
		inRetVal = VS_SUCCESS;
		LOG_PRINTFF((0x08L, "ALL TC UPLAOD SUCCESS"));
    } else {
        inRetVal = VS_ERR;
    }
    return(inRetVal);
}

/*********************************************************************************************
* @func void | vdCPACSetMT0510Error |
* This function sets the error returned in an MT 0510 packet.
*
* @parm TRANSACTION_OBJECT * | pobTran |
*       This is the transaction object.
*
* @end
**********************************************************************************************/

void vdCPACSetMT0510Error(TRANSACTION_OBJECT* pobTran) {
    char szSettleMsg[RESP_MSG_SIZE + 1],
    szSettleResponse[RESP_MSG_SIZE + 1];

    if ((strlen((char *) srISO.pszField44) > 0) && (strncmp((char *) srISO.pszField44, "00", 2))) {
        vdDisplayResponseString((char *) srISO.pszField44);

        vdSGErrorMessage(SETTLE_FAIL_ERR_MSG);
        strcpy(szSettleResponse, "Stl Failed- Response : ");
        strcat(szSettleResponse, (char *) srISO.pszField39);
        ACTIVITY_LOG(szSettleResponse);
        /* citi_phil_DSC_don_27feb */
    } else if (strncmp((char *) srISO.pszField39, "00", 2)) {
        /*
           *      Do Not Overwrite previously set error messages.
            */
        if (lnGGErrorMessage() == 0L) {
            //1.4 vipin_philippines_DSC_Don_27Feb
            //vdGetMessageFromFile( AMEX_ERROR_MSG15, szSettleMsg);
            //strcat(szSettleMsg, (char *)srISO.pszField39);
            //vdSGRespMsg(szSettleMsg);
            // added the next 4 lines to display the settlement response.
            vdGetMessageFromThisFile(CPAC_RESPONSE_FILE, atoi((char *) srISO.pszField39), szSettleMsg);
            inMLDisplayAt(1, 8, szSettleMsg, CLR_EOL, ML_USE_GIVEN_FONT, ML_ACTION_FONT, "F:ASC8X21.VFT");
            vdSGRespMsg(szSettleMsg);
            ACTIVITY_LOG(szSettleMsg);
        }
    } else if (strlen((char *) srISO.pszField62) > 0)  // CPAC_UNBK changed 63-> 62
    {
        //        strlcpy(pobTran->szRespMsg, (char *)srISO.pszField63, 20);
    }

    vdSGErrorMessage(SETTLE_FAIL_ERR_MSG);
}

/*********************************************************************************************
* @func int | inReconcileCPAC |
* This function sends the 0500 Settlement request to the
* host and gets the response.  If there was a totals mismatch
* it will call an other function inCPACSendDetailRecords to upload
* all the batch records to the host.
*
* @parm TRANSACTION_OBJECT * | pobTran |
*       This is the transaction object.
*
* @flag int | VS_ERR
* @flag int | VS_SUCCESS
* @end
**********************************************************************************************/

int inReconcileCPAC(TRANSACTION_OBJECT* pobTran) {
    int inRetVal;
    short shTranCode;
    short shPIPTransCode;
    short fBatchUpload; //jzg 05-Mar-05  spqalog011
    char szSettleMsg[RESP_MSG_SIZE + 1];
    int inTemp;

    /** /pdebug(("--inReconcileCPAC--"));*/

    if (inCPACCreateVariantStruct60() == VS_ERR) {
        vdFree((char *) psrVariant60);
        vdSGErrorMessage(NO_MEM_ERR_MSG);
        return(VS_ERR);
    }

       //START: Praveen_s1 20042005 - To Fix the Field 2 Corruption in Amex settlement .
    if(strcmp(szGetHostFileName(), "AXAP") == 0)
    {
/*
        if (inAXAPCreateVariantStruct63() == VS_ERR){
	        vdFreeVariantTables();
	        vdSGErrorMessage(NO_MEM_ERR_MSG);
	        return(VS_ERR);
    	}
*/ //LIEM DISABLE
    }
   else
   {
	    if (inCPACCreateVariantStruct63() == VS_ERR) {
	        vdFreeVariantTables();
	        vdSGErrorMessage(NO_MEM_ERR_MSG);
	        return(VS_ERR);
	    }
   }
       //END: Praveen_s1 20042005 - To Fix the Field 2 Corruption in Amex settlement .

    if ((psrHostData = psrCreateHostData()) == (HOST_8583_DATA *) NULL_CH) {
        vdFreeHostData(psrHostData);
        vdFreeVariantTables();
        vdSGErrorMessage(NO_MEM_ERR_MSG);
        return (VS_ERR);
    }


    if ((psrHostData->c8583_data = psrCreateCommData(pobTran, CPAC_SEND_SIZE, VS_FALSE)) == (COMM_8583_DATA *) NULL_CH) {
        vdSGErrorMessage(NO_MEM_ERR_MSG);
        vdFreeISO8583Data(psrHostData);
        return (VS_ERR);
    }

	psrHostData->c8583_data->transceiver = inImamTxRx8583;  //
#ifdef MODEM
	if (inGetUCLCommLink()==0) {  // to get resp timeout
		MODEM_OBJECT *obModem;
		obModem = (MODEM_OBJECT *)obCommunication.Data;
		psrHostData->c8583_data->comm_timeout         = obModem->shGetRespTimeOut(obModem->srCPT);  // for Response TimeOut
		psrHostData->c8583_data->wait_for_carrier     = obModem->shGetCarrierTimeOut(obModem->srCPT); // for Carier TimeOut
	}
#endif

    ((VALIDATION_STRUCT *) (psrHostData->c8583_data->v_parms))->comm_struct = psrHostData->c8583_data;

    /** Added fix for duplicate Advice **/
    psrHostData->c8583_data->validation = (PFI_PVOID_INT) inCPACBaseRespValidation; //dup_adv

    vdSGCode(CLS_BATCH);        /* Start of batch settlement */

    shTranCode = inGGCode();
    inTemp = inStoreTranFlexiData(pobTran, AMEX_PIP_TRANS_CODE, (unsigned char *) &shTranCode, 2);
    /* Disable reversal handling while doing close processing */
    psrHostData->reverse_flag = 0;
    psrHostData->c8583_data->validation = (PFI_PVOID_INT) inBaseValidationLow;


    if ((shPIPTransCode = shLoadPIPTransCode(shTranCode)) == VS_ERR) {
        vdFreeISO8583Data(psrHostData);
        return (VS_ERR);
    }

    errno = 0;
    inRetVal = pip_trans((int) shPIPTransCode, psrHostData);

    vdFreeISO8583Data(psrHostData);
/*
    //START: Praveen_s1 18042005 - To Display Response Msg from Feld63 in Host Response as per Amex Specification
	if((strcmp(szGetHostFileName(), "AXAP") == 0) && ((inRetVal == HOST_ERROR) || (inRetVal == PIP_APPROVAL))) //Praveen 20042005
		vdAXAPDisplayFld63RespMsg();
    //END: Praveen_s1 18042005 - To Display Response Msg from Feld63 in Host Response as per Amex Specification
*/ //LIEM DISABLE THIS
    if (inRetVal == HOST_ERROR) {
        vdSetMustSettleFlag(VS_TRUE);
        /*     inSaveHostData (inGetCDTHostIndex()); sadiq 1.4 changed still need to verify */
        inSaveHostData(inGetHostHandle());  /* Amex pip calls inSaveMHTRec */

        /* Response code of 95 is Totals Mismatch - Details upload */
        if (!strcmp((char *) srISO.pszField39, "95"))
        {	fBatchUpload = VS_TRUE;
            inStoreTranFlexiData(pobTran, CITI_BATCH_UPLOAD_FLAG, (unsigned char *) &fBatchUpload, 2);

            inRetVal = inCPACSendDetailRecords(pobTran);
		}
        else {
            /*Display error message from the host - DH1*/
	     if(strcmp(szGetHostFileName(), "AXAP") != 0)		//Praveen 18042005 - For Amex the Msg has been displayed from Field63
            vdCPACSetMT0510Error(pobTran);
            inRetVal = VS_ERR;
        }
    } else {
        if ((inRetVal == PIP_APPROVAL) && (!strcmp((char *) srISO.pszField39, "00"))) {


		if (inResetBatch(pobTran) != VS_SUCCESS)
                return(VS_ERR);


            vdGetMessageFromFile(SETTLE_SUCCESS_MSG, szSettleMsg);
            /* Set the GDS response message field for storage
                                          to the batch history report file  - JB4 */
            //            strlcpy((char *)pobTran->szRespMsg, (char *)srISO.pszField63, 20);

            return(VS_SUCCESS);
        }
        if (inRetVal == PROT8583_FAILED_TRANSMIT) {
            vdSetMustSettleFlag(VS_TRUE);
            /*     inSaveHostData (inGetCDTHostIndex()); sadiq 1.4 changed still need to verify */
            inSaveHostData(inGetHostHandle());  /* Amex pip calls inSaveMHTRec */
        }

	//spqalog045
	 vdSetMustSettleFlag(VS_TRUE);
        /*     inSaveHostData (inGetCDTHostIndex()); sadiq 1.4 changed still need to verify */
        inSaveHostData(inGetHostHandle());  /* Amex pip calls inSaveMHTRec */

        vdSGErrorMessage(SETTLE_FAIL_ERR_MSG);
        ACTIVITY_LOG("PROT8583_FAILED_TRANSMIT");
        /* citiphil_don_27feb_DSC */
        inRetVal = VS_ERR;
    }

    return (inRetVal);
}

/*********************************************************************************************
* @func int | inFinalCPACRecon |
* This function sends the 0500 Settlement request to the host and gets the response.
* This function is called after batch upload.
*
* @parm TRANSACTION_OBJECT * | pobTran |
*       This is the transaction object.
*
* @flag int | VS_ERR
* @flag int | VS_SUCCESS
* @end
**********************************************************************************************/

int inFinalCPACRecon(TRANSACTION_OBJECT* pobTran) {
    int inRetVal;
    short shTranCode;
    short shPIPTransCode;
    char szSettleMsg[RESP_MSG_SIZE + 1],
    szSettleResp[RESP_MSG_SIZE + 1];

    /** /pdebug(("--inFinalCPACRecon--"));*/

    if (inCPACCreateVariantStruct60() == VS_ERR) {
        vdFree((char *) psrVariant60);
        vdSGErrorMessage(NO_MEM_ERR_MSG);
        return(VS_ERR);
    }

   //START: Praveen_s1 14042005 - To Fix the Amex settlement Issue in case of settlement with 5 online transactions.
    if(strcmp(szGetHostFileName(), "AXAP") == 0)
    {
/*
        if (inAXAPCreateVariantStruct63() == VS_ERR){
	        vdFreeVariantTables();
	        vdSGErrorMessage(NO_MEM_ERR_MSG);
	        return(VS_ERR);
    	}
*/ //LIEM DISABLE
    }
   else
   {
   	 if (inCPACCreateVariantStruct63() == VS_ERR)
	 {
	        vdFreeVariantTables();
	        vdSGErrorMessage(NO_MEM_ERR_MSG);
	        return(VS_ERR);
    	}
   }
   //END: Praveen_s1 14042005 - To Fix the Amex settlement Issue in case of settlement with 5 online transactions.

    if ((psrHostData = psrCreateHostData()) == (HOST_8583_DATA *) NULL_CH) {
        vdFreeHostData(psrHostData);
        vdFreeVariantTables();
        vdSGErrorMessage(NO_MEM_ERR_MSG);
        return (VS_ERR);
    }


    if ((psrHostData->c8583_data = psrCreateCommData(pobTran, CPAC_SEND_SIZE, VS_FALSE)) == (COMM_8583_DATA *) NULL_CH) {
        vdSGErrorMessage(NO_MEM_ERR_MSG);
        vdFreeISO8583Data(psrHostData);
        return (VS_ERR);
    }

	psrHostData->c8583_data->transceiver = inImamTxRx8583;  //
#ifdef MODEM
	if (inGetUCLCommLink()==0) {  // to get resp timeout
		MODEM_OBJECT *obModem;
		obModem = (MODEM_OBJECT *)obCommunication.Data;
		psrHostData->c8583_data->comm_timeout         = obModem->shGetRespTimeOut(obModem->srCPT);  // for Response TimeOut
		psrHostData->c8583_data->wait_for_carrier     = obModem->shGetCarrierTimeOut(obModem->srCPT); // for Carier TimeOut
	}
#endif

    ((VALIDATION_STRUCT *) (psrHostData->c8583_data->v_parms))->comm_struct = psrHostData->c8583_data;
    /** Added fix for duplicate Advice **/
    psrHostData->c8583_data->validation = (PFI_PVOID_INT) inCPACBaseRespValidation;  //dup_adv



    vdSGCode(CLS_BATCH_UPLOAD); /* End of Batch settlement */

    shTranCode = inGGCode();

    /* Disable reversal handling for batch close */
    psrHostData->reverse_flag = 0;

    /** /pdebug (("TranCode = %d", inTranCode));*/
    inStoreTranFlexiData(pobTran, AMEX_PIP_TRANS_CODE, (unsigned char *) &shTranCode, 2);

    if ((shPIPTransCode = shLoadPIPTransCode(shTranCode)) == VS_ERR) {
        vdFreeISO8583Data(psrHostData);
        return (VS_ERR);
    }

    /** /pdebug (("PIPTranCode = %d", inPIPTransCode));*/
    inRetVal = pip_trans((int) shPIPTransCode, psrHostData);

    vdFreeISO8583Data(psrHostData);
/*
    //START: Praveen_s1 18042005 - To Display Response Msg from Feld63 in Host Response as per Amex Specification
	if((strcmp(szGetHostFileName(), "AXAP") == 0) && ((inRetVal == HOST_ERROR) || (inRetVal == PIP_APPROVAL))) //Praveen 20042005
		vdAXAPDisplayFld63RespMsg();
    //END: Praveen_s1 18042005 - To Display Response Msg from Feld63 in Host Response as per Amex Specification
*/ //LIEM Disable This
    if (inRetVal == HOST_ERROR) {
	 if(strcmp(szGetHostFileName(), "AXAP") != 0)	//Praveen 18042005 - For Amex Msg has been displayed from field 63
        	vdCPACSetMT0510Error(pobTran);
        return(VS_ERR);
    } else {
        if ((inRetVal == PIP_APPROVAL) && (!strcmp((char *) srISO.pszField39, "00"))) {
            /* Do some final stage clean-up work */
       	//Shifted to just before batch deletion to fix the batch number increment issue
            /*if (inResetBatch(pobTran) != VS_SUCCESS)
            {
                return(VS_ERR);
            }*/

            vdGetMessageFromFile(SETTLE_SUCCESS_MSG, szSettleMsg);
            /* Set the GDS response message field for storage
                                          to the batch history report file  - JB4 */
            //            strlcpy(pobTran->szRespMsg, (char *)srISO.pszField63, 20);
            return(VS_SUCCESS);
        }

        vdSGErrorMessage(SETTLE_FAIL_ERR_MSG);
        sprintf(szSettleResp, "Pip= %d Resp= %s", inRetVal, (char *) srISO.pszField39);
        ACTIVITY_LOG(szSettleResp);
        /* Citi_phil_1.4_don_27feb_DSC */
        return(VS_ERR);
    }
}

/*********************************************************************************************
* @func int | inSettleCPAC |
* This is the main function which is called to settle with the CPAC host.
*
* @parm PROTOCOL_OBJECT * |pobProtocol |
*       Protocol object
*
* @parm PACKET_OBJECT * |pobPacket |
*       Packet object
*
* @flag int | VS_ERR
* @flag int | VS_SUCCESS
* @end
**********************************************************************************************/

int inSettleCPAC(PROTOCOL_OBJECT* pobProtocol,PACKET_OBJECT* pobPacket) {
    long lnSTAN; //, lnBatchNum; CPAC_LINT_RMD
    int inResult = VS_SUCCESS;
    long lnCount,
    lnAdviceExist;
    int inAdviceHandle;
    char szFileName[FILENAME_SIZE + 1];
    char szDate[DATE_SIZE + 1];
    char szTime[TIME_SIZE + 1];
#ifdef ICICI
   int inHostNum;
#endif
   short fBatchUpload; // spqalog011
    //char szSettleMsg[RESP_MSG_SIZE + 1]; CPAC_LINT_RMD
    TRANSACTION_OBJECT* pobTran;

    /** /pdebug(("--inSettleCPAC--"));*/

    pobTran = (TRANSACTION_OBJECT *) pobPacket->Transaction;

    /* check the batch totals */
    if (inCheckBatchTotals(pobTran, &lnCount))
        return(VS_ERR);

    /** /pdebug(("Count=%ld",lnCount));*/
    /* Determine if there are any advices to be transmitted */

    /*   vdGetReversalFileName(szFileName, inGetCDTHostIndex()); sadiq 1.4 changed */
    vdGetReversalFileName(szFileName, inGetHostHandle());

    strcat(szFileName, OFFLINE_FILE_EXTN);
    inAdviceHandle = open(szFileName, O_RDONLY);

    lnAdviceExist = seek_ivlr(inAdviceHandle, 1L, SEEK_SET);
    close(inAdviceHandle);
    /** /pdebug(("Advice=%ld",lnAdviceExist));*/




    /* else communicate settlement */

    if (obCommunication.inBegin)
        if (obCommunication.inBegin(&obCommunication, shGetCommunicationIndex(), VS_TRUE) != VS_SUCCESS)//CPAC2.1B
            return(VS_ERR);

    SVC_WAIT(1000);

    if (obCommunication.inCheck)
        if (obCommunication.inCheck(&obCommunication) != VS_SUCCESS)
            return(VS_ERR);
    SVC_WAIT(1000);

    //1.4 till here..


    /* Increment the STAN */
    if (inIncSTAN() != VS_SUCCESS)
        return(VS_ERR);

    /* First upload all the offline records in order to update the
        host data-base */
#ifndef TLFB
    lnSTAN = lnGetSTAN();
#endif /* nTLFB */
    /* DCP approvals require use of reversal allocated space */
    if (inUploadCPACAdvices(VS_TRUE, pobTran) != VS_SUCCESS) {
        vdSetMustSettleFlag(VS_TRUE);
        /*     inSaveHostData (inGetCDTHostIndex()); sadiq 1.4 changed still need to verify */
        inSaveHostData(inGetHostHandle());  /* Amex pip calls inSaveMHTRec */
        inResult = VS_ERR;
    } else {
#ifdef TLFB
        lnSTAN = lnGetSTAN();
#endif /* TLFB */
        pobTran->srBRec.lnSTAN = lnSTAN;
        pobTran->srBKey.lnOrgSTAN = pobTran->srBRec.lnSTAN;

#ifdef VXEMVAPP
	if (inImamSendAllTC(pobTran) != VS_SUCCESS){
	//if(inEMVSendTCAdvice(pobTran, pobPacket)!= VS_SUCCESS) { 
	  vdSetMustSettleFlag(VS_TRUE);
      inSaveHostData(inGetHostHandle());  /* Amex pip calls inSaveMHTRec */
	  inResult = VS_ERR;
    } else {
#endif

        /* Now try to reconcile with the host : Send the totals in the
            0500 message first, if the totals do not match upload the
            entire batch and send the totals again */

        vdSGCode(CLS_BATCH);

        if (inReconcileCPAC(pobTran) != VS_SUCCESS) {
            vdGetDate(szDate, MMDDYY);
            strcpy(pobTran->szSettDate, szDate);
            vdGetTime(szTime);
            strlcpy(pobTran->szSettTime, szTime, DATE_SIZE);
            inResult = VS_ERR;
            vdDisplayStatusString(pobTran->szRespMsg);
            SVC_WAIT(1000);
        } else {
            /* make sure transaction processing is enabled*/
            vdSetMustSettleFlag(VS_FALSE);
            /* Disk write */
            /*     inSaveHostData (inGetCDTHostIndex()); sadiq 1.4 changed still need to verify */
            inSaveHostData(inGetHostHandle());  /* Amex pip calls inSaveMHTRec */

            strlcpy((char *) pobTran->szSettTime, (char *) srISO.pszField12, TIME_SIZE);
            /*
             *      Expand DATE to full size, in YYMMDD format.
             */
            //vdGetDate (pobTran->szSettDate, 0);
            //memcpy (&pobTran->szSettDate[2], (char *)srISO.pszField13, DATE_SIZE-2);
            memcpy(&pobTran->szSettDate[0], (char *) srISO.pszField13, DATE_SIZE);
            vdGetDate(szDate, MMDDYY);
            strcat(&pobTran->szSettDate[4], &szDate[4]);
        }
     #ifdef VXEMVAPP //Added by Thiru
      }
    #endif
    }

    //spqalog011
    // Used to fix Batch Number increment during Settlement with Batch Upload jzg 05-Mar-05
	        inGetTranFlexiData(pobTran, CITI_BATCH_UPLOAD_FLAG, (unsigned char *) &fBatchUpload, 2);
	        if (fBatchUpload==1)
	        {
			// end-of-update
    			/* increment the invoice number for successful and unsuccessful settlements */
    			inIncInvNum(/*pobTran*/);
		}

#ifdef ICICI
//memset (pobTran, 0, sizeof(TRANSACTION_OBJECT));  // LENZ

    inHostNum = shGetHostGroupRef();
	if ( inLoadHDTRec(inHostNum) == VS_SUCCESS)
	{
		   if(strcmp(szGetHostFileName(), "ICIC") == 0)
		   {
    inLoadTRTRec(pobTran, LOGON);
    pobTran->srTRTRec.TransactionCode = LOGON;
    vdSGCode(LOGON);
    pobTran->inTransactionCode = LOGON;
    //vdSGCode(LOGON);
    // pobTran->inTransactionCode=LOGON;
     pobTran->srBKey.lnOrgSTAN = pobTran->srBRec.lnSTAN;
     inIncSTAN(); /* increment the STAN for new transaction to host */
    pobTran->srBRec.lnSTAN = lnGetSTAN();/*Increment the stan for the LOGON txn*/
   // inRunFunction(pobTran, BUILD_AND_SEND_PACKET);
     pobTran->srBKey.fVoided = VS_FALSE;
    if(inSendReceiveHDFC(pobProtocol,  pobPacket) == VS_SUCCESS)
    	{
          if(inRunFunction(pobTran, CITI_SAVE_KEYS) == VS_SUCCESS)
	 {
              inRunFunction(pobTran, CPAC_DISPLAY_RESPONSE);
              inRunFunction(pobTran,ICICI_LOGON_STATUS_MSG);
         }
    	}
	else
		inRunFunction(pobTran, ICICI_LOGON_FAIL_MSG1);
		   	}
		}

#else

	vdSGCode(SETTLE);

//jrd to empty screen display of AXAP field63. Fixed due to settle all
 vdDisplayAt(1, 3, " ", CLR_LINE);
 vdDisplayAt(1, 4,  " ", CLR_LINE);
 vdDisplayAt(1, 5, " ", CLR_LINE);
 vdDisplayAt(1, 6, " ", CLR_LINE);

#endif  /* ICICI  */
    if (obCommunication.inEnd)
        #if 1 //kv1 debug 29-oct-2001, inclosesdlc no longer exists
        obCommunication.inEnd(&obCommunication);
#else
    // ORIG_CODE if (obCommunication.inEnd(&obCommunication) == VS_ERR)
    if ((*(int(*) (COMM_OBJECT *)) obCommunication.inEnd) (&obCommunication) == VS_ERR) {
        MODEM_OBJECT* obModem;
        obCommunication.fLinkUp = VS_FALSE;
        obModem = (MODEM_OBJECT *) obCommunication.Data;
        //inCloseSDLC(obModem->hModem, obModem->srCPT.inBaudRate);
        // ORIGINAL_CODE inCloseSDLC(obModem->hModem, (obModem->shGetBaudRate(obModem->srCPT)));
        inCloseSDLC(obModem->hModem, ((*(int(*) (CPT_REC)) obModem->shGetBaudRate) (obModem->srCPT)));
        obModem->hModem = 0;
    }
#endif
    return(inResult);
}


/*-------------------------------------------------------------------------
 * Routine Name : int inCPACCheckAndDoAutoSettle(int)
 * Description  : Checks if time for auto settlement for the specified host.
 * Inputs       : None
 * Outputs      : None
 * Returns      : VB_TRUE / VB_FALSE
 * Notes        :
 *------------------------------------------------------------------------
 */
int inCPACCheckAndDoAutoSettle(TRANSACTION_OBJECT* pobTran) {
    static int inIdleLoopTimeOut = 0,
    inCPACAuto = 0,
    inStatHostIndex = 0;
    static int inMCnt = 0,
    inDMCnt = 0;
    static int inHCnt = 0,
    inDHCnt = 0;
    int intries = 0,
    inRetries = 0;
    int inNoOfHDTRecs,
    inNoOfMITRecs,
    inRetSettleVal,
    inRetVal = VS_SUCCESS,
    inHostNum = 1; /*, inResult;    */
    char szHostName[HOST_NAME_SIZE + 1];
    char szCurDateTime[CPAC_DATE_TIME_SIZE + 1 + 1],                  /* YYYYMMDDHHMM */
    szAutoSettleDateTime[CPAC_DATE_TIME_SIZE + 1]; //, szFont[FILENAME_SIZE + 1];
    //  char szCPACDate[DATE_SIZE + 1], szDate[DATE_SIZE + 1], szAmt[AMT_SIZE + 1];
    char chDummy[100 + 1]; //changed from 20 cpac_2.2a**********!!!!!

    if (inGlobalAutoHandle != 1) {
        inGlobalAutoHandle = 0;
        vdSGErrorMessage(0L);
        return(BRANCH_EXIT);
    } else {
        inGlobalAutoHandle = 0; {
            if (fGetAutoSettle()) {
                inNoOfMITRecs = inGetMITTotRecs();
                inNoOfHDTRecs = inGetHDTTotRecs();

                if (inMCnt > inNoOfMITRecs - 1)
                    inMCnt = 0;

                inLoadMITRec(inMCnt);
                inGlobalMerchantHandle = inGetMerchantNum();//CPAC2.1B
                if (inHCnt < inNoOfHDTRecs) {
                    inLoadHDTRec(inHCnt);
                    vdSetHostHandle(inHCnt);

                    if ((fCPACGetMerchEnable()) == TRUE) {
                        strcpy(szHostName, szGetHostFileName());

                        vdLoadCPACParams(&srCPAC);

                        vdGetCPACAutoSettleDtTime(&srCPAC, szAutoSettleDateTime);

                        if ((strlen(szAutoSettleDateTime) == 0) || (strlen(szAutoSettleDateTime) < CPAC_DATE_TIME_SIZE)) {
                            vdSGErrorMessage(0L);
                            return(BRANCH_EXIT); /* Dont do anything, just continue : Auto settle disabled */
                        }
                        /* Current date and time in YYYYMMDDHHMMSS format */

                        inGetDateTime(szCurDateTime);

                        if (strcmp(szCurDateTime, szAutoSettleDateTime) >= 0) {
                            /* Its time for auto setlement!! */

                            //***  get_font(szFont);
                            //***  set_font(ASC8X21_VFT);   //leo_apr22
                            //***vdSetGridParams(0);

                            if (fChkHostBatches(pobTran, inMCnt) == VS_TRUE) {
                                inHCnt++;
                                if (inHCnt > inNoOfHDTRecs - 1) {
                                    inHCnt = 0;
                                    inMCnt++;
                                }

                                //set_font (szFont);
                                //vdSetGridParams(2);  //test_vipin
                                //vdSGErrorMessage(0L);
                                //vdSelectMenu(ROOT_MENU_ID);

                                vdSGErrorMessage(0L);
                                return(BRANCH_EXIT);
                            }

                            inRetries = inGetAutoSettRetries();
                            while (intries < inRetries) {
                                //    pstGetSet_pobTran (pobTran, 1, &inResult); //leo_apr24/* set the address */   (Commented to fix the POBTRAN USE ERROR bug Saritha_b1)
                                //vdClearASCII8x21Window(1, 1, 21, 8);
                                clrscr();
                                // to be put back later!!!!!! vdSGAutoSettle(VS_TRUE);
                                //                        if ((inRetSettleVal = pSettleAllHosts((TRANSACTION_OBJECT *)&pobTran)) == VS_SUCCESS)  // CPAC_LINT_ADDED (TRANSACTION_OBJECT *)
                                // srHDTRec.inSettlementType = 0;  // Do not prompt for the amount.
                                vdSetSettlementType(0);// CPAC2.1B
                                inRetSettleVal = inRunOperation(pobTran, AUTO_SETTLE_OPERATION);

                                if (inRetSettleVal == VS_SUCCESS) {
                                    //inRetSettleVal = VS_SUCCESS;  CPAC_LINT_RMD
                                    //inLoadMITRec(inMCnt);
                                    //inLoadHDTRec(inHCnt);
                                    //vdLoadCPACParams(&srCPAC);
                                    inChangeAutoSetlDate(inStatHostIndex);
                                    //pstGetSet_pobTran (pobTran, 2, &inResult);//leo_apr24  (saritha commented)
                                    shSetPFRState(pobTran, PFR_IDLE_STATE, 0, 0, (unsigned char *) chDummy);// No subrecord information
                                    break;
                                }

                                if (inRetSettleVal == VS_ESCAPE) {
                                    inRetVal = VS_ESCAPE;
                                    inChangeAutoSetlDate(inHostNum);
                                    // pstGetSet_pobTran (pobTran, 2, &inResult);//leo_apr24         (saritha commented)
                                    break;
                                }

                                intries++;

                                //  pstGetSet_pobTran (pobTran, 2, &inResult);//leo_apr24   (saritha commented)
                            }  // while the retries

                            if (intries >= inRetries)
                                inChangeAutoSetlDate(inHostNum);     //leo_apr24/* set the address */

                            //set_font (szFont);
                            //vdSetGridParams(2); //test_vipin
                            vdSGErrorMessage(0L);
                            //vdSelectMenu(ROOT_MENU_ID);   //leo_apr22/* Return to idle if failed */
                        }    // if - autosettle
                    }  // End of if Merchant enabled for that particular hosts
                    inHCnt++;

                    if (inHCnt > inNoOfHDTRecs - 1) {
                        inHCnt = 0;
                        inMCnt++;
                    }
                } // End of No. of Hosts
            } // End of Autosettle flag is enabled

            //set_font (szFont);
            //vdSetGridParams(2);
            vdSGErrorMessage(0L);
            // vdSelectMenu(ROOT_MENU_ID);
        }  /* CPAC_AUTO_SETTLE_LOOK_UP_TIME */
    } // End of inGlobalAutoHandle is set

    //if (inRetVal != VS_SUCCESS) inRetVal = VS_ERR;
    vdSGErrorMessage(0L);
    return(BRANCH_EXIT);
}

/*-------------------------------------------------------------------------
 * Routine Name : int inChangeAutoSetlDate(int inHostNum)
 * Description  : Changes the autosettlement date to the next day,
 *                same time and updates the TCT
 * Inputs       : None
 * Outputs      : None
 * Returns      : VS_SUCCESS
 * Notes        :
 *------------------------------------------------------------------------
 */
static int inChangeAutoSetlDate(int inHostNum) {
    char szTemp[5 + 1],
    szTempDateTime[CPAC_DATE_TIME_SIZE + 1],
    szCurrentDateTime[CPAC_DATE_TIME_SIZE + 1],
    szAutoSettleDateTime[CPAC_DATE_TIME_SIZE + 1];
    char szYYYY[8 + 1],
    szYYYY1[8 + 1];
    char szHostName[HOST_NAME_SIZE + 1],
    szHDTLocalHostFileName[HOST_NAME_SIZE + 1];
    int inYear,
    inMonth,
    inDay,
    inMonthEnd,
    inTimeGap,
    inHours,
    inMints,
    inSecs,
    inDiffDays,
    inDiffHours,
    inDayDiff = 0,
    inHourDiff = 0;
    int inMerchantNum = 0;
    /* , inResult; CPAC_LINT_REMOVED */
    //   CPAC_REC srCPAC;

    memset(szCurrentDateTime, 0, sizeof(szCurrentDateTime));
    memset(szAutoSettleDateTime, 0, sizeof(szAutoSettleDateTime));
    memset(szTemp, 0, sizeof(szTemp));
    memset(szTempDateTime, 0, sizeof(szTempDateTime));

    memset(szYYYY, 0, sizeof(szYYYY)); //cpac_2.2a added for memory leak
    memset(szYYYY1, 0, sizeof(szYYYY1));


    /* Auto settle date and time in YYYYMMDDHHMMSS format */
    //inResult =
    inGetDateTime(szCurrentDateTime);
    //if (inResult = VS_ERR) return (VS_ERR);
    vdGetCPACAutoSettleDtTime(&srCPAC, szAutoSettleDateTime);
    if (strlen(szAutoSettleDateTime) == 0)
        return (VS_SUCCESS);
    /* If the autosettle dt is null, Autosettle is disabled */

    memcpy(szYYYY, szCurrentDateTime, 8);
    memcpy(szYYYY1, szAutoSettleDateTime, 8);
    if ((strcmp(szYYYY1, szYYYY)) < 0) {
        memcpy(szTemp, szCurrentDateTime, 4);
        inYear = atoi(szTemp);
        memset(szTemp, 0, sizeof(szTemp));
        memcpy(szTemp, &szCurrentDateTime[4], 2);
        inMonth = atoi(szTemp);
        memset(szTemp, 0, sizeof(szTemp));
        memcpy(szTemp, &szCurrentDateTime[6], 2);
        inDay = atoi(szTemp);
        memset(szTemp, 0, sizeof(szTemp));
        memcpy(szTemp, &szCurrentDateTime[8], 2);

        inHours = atoi(szTemp);
        memset(szTemp, 0, sizeof(szTemp));
        memcpy(szTemp, &szCurrentDateTime[10], 2);
        inMints = atoi(szTemp);
        memset(szTemp, 0, sizeof(szTemp));
        memcpy(szTemp, &szCurrentDateTime[12], 2);
        inSecs = atoi(szTemp);
    } else {
        memcpy(szTemp, szAutoSettleDateTime, 4);
        inYear = atoi(szTemp);
        memset(szTemp, 0, sizeof(szTemp));
        memcpy(szTemp, &szAutoSettleDateTime[4], 2);
        inMonth = atoi(szTemp);
        memset(szTemp, 0, sizeof(szTemp));
        memcpy(szTemp, &szAutoSettleDateTime[6], 2);
        inDay = atoi(szTemp);
        memset(szTemp, 0, sizeof(szTemp));
        memcpy(szTemp, &szAutoSettleDateTime[8], 2);

        inHours = atoi(szTemp);
        memset(szTemp, 0, sizeof(szTemp));
        memcpy(szTemp, &szAutoSettleDateTime[10], 2);
        inMints = atoi(szTemp);
        memset(szTemp, 0, sizeof(szTemp));
        memcpy(szTemp, &szAutoSettleDateTime[12], 2);
        inSecs = atoi(szTemp);
    }

    inTimeGap = inGetCPACTimeGap(&srCPAC);      //Gets the time gap in hours

    inDiffDays = inTimeGap / HOURS_PER_DAY;
    inDiffHours = inTimeGap % HOURS_PER_DAY;

    inHours += inDiffHours;

    if (inHours > 23) {
        inDiffDays++; inHours -= HOURS_PER_DAY;
    }

    /* Assuming that the max hour gap will not exceed 2 months ! */
    if (inDiffDays > 0) {
        inDay += inDiffDays;
        inMonthEnd = month_end(inMonth, inYear);
        if (inDay > inMonthEnd) {
            inDay = inDay - inMonthEnd;
            inMonth = ((inMonth % 12) + 1);
            if (inMonth == 1)
                inYear++;
            inMonthEnd = month_end(inMonth, inYear);
            if (inDay > inMonthEnd) {
                inDay -= inMonthEnd;
                inMonth = ((inMonth % 12) + 1);
                if (inMonth == 1)
                    inYear++;
            }
        }
    }
    sprintf(szTempDateTime, "%04d%02d%02d%02d%02d%02d", inYear, inMonth, inDay, inHours, inMints, inSecs);


    //  vdLoadCPACParams( &srCPAC );

    strlcpy(srCPAC.szCPACAutoSettleDtTm, szTempDateTime, CPAC_DATE_TIME_SIZE);
    //strcpy(szHostName, szGetHostName());//CPAC2.1B
	strcpy (szHostName , szGetHostFileName());// To utilize HostFileName

    strcpy(szHDTLocalHostFileName, szHostName);
    vdTrimSpaces(szHDTLocalHostFileName);
    strcat(szHDTLocalHostFileName, ".dat");

    inMerchantNum = inGetMerchantNum() - 1;

    if (inSaveConfRec(szHDTLocalHostFileName, SIZE_CPAC_REC, inMerchantNum, (char *) &srCPAC) != VS_SUCCESS) {
        pdebug(("inSaveCPACRecErr=%d", 0));
        vdSGErrorMessage(MIT_ERR_MSG21);
        return(VS_ERR);
    }

    return(VS_SUCCESS);
}



/*-----------------------------------------------------------------------------
 * Routine Name : int inGetDateTime(pszDateTime)
 * Description  : Gets the date and time in YYYYMMDDHHMMSS format
 *                pszDateTime should be allocated outside, the
 *                size should be 14 + 1 bytes.
 * Inputs       : pszDateTime  - Pointer where the Date/time will be stored.
 * Outputs      :
 * Notes        :
 *-----------------------------------------------------------------------------
*/
int inGetDateTime(char* pszDateTime) {
    /*
           if (read(hClock, pszDateTime, CPAC_DATE_TIME_SIZE) != CPAC_DATE_TIME_SIZE)
               return(VS_ERR);
    */
    memset(pszDateTime, 0x00, sizeof(pszDateTime));
    if (SVC_CLOCK(GET_CLOCK, (char *) pszDateTime, 15 /*CPAC_DATE_TIME_SIZE + 1*/) != 15 /* CPAC_DATE_TIME_SIZE */)
        return(VS_ERR);

    pszDateTime[CPAC_DATE_TIME_SIZE] = NULL_CH;
    return (VS_SUCCESS);
}



/*-------------------------------------------------------------------------
 * Routine Name : void vdGetCPACAutoSettleDtTime(CPAC_REC *srCPAC,char *pchAutoSettle)
 * Description  : Gets the autosettle date and time.
 * Inputs       : None
 * Outputs      : None
 * Returns      : VS_SUCCESS
 * Notes        :
 *------------------------------------------------------------------------
 */

void vdGetCPACAutoSettleDtTime(CPAC_REC* srCPAC,char* pchAutoSettle) {
    //  CPAC_REC srCPAC;

    //vdLoadCPACParams( &srCPAC );
    strlcpy(pchAutoSettle, srCPAC->szCPACAutoSettleDtTm, CPAC_DATE_TIME_SIZE);
}



/*-------------------------------------------------------------------------
 * Routine Name : void vdSetCPACAutoSettleDtTime(char *pchAutoSettle)
 * Description  : Sets the autosettle date and time.
 * Inputs       : None
 * Outputs      : None
 * Returns      : VS_SUCCESS
 * Notes        :
 *------------------------------------------------------------------------
 */

void vdSetCPACAutoSettleDtTime(char* pchAutoSettle) {
    //  CPAC_REC srCPAC;

    vdLoadCPACParams(&srCPAC);
    strlcpy(srCPAC.szCPACAutoSettleDtTm, pchAutoSettle, CPAC_DATE_TIME_SIZE);
}


/*-------------------------------------------------------------------------
 * Routine Name : int  inGetCPACTimeGap(CPAC_REC  *srCPAC)
 * Description  : Gets the autosettle date and time.
 * Inputs       : None
 * Outputs      : None
 * Returns      : VS_SUCCESS
 * Notes        :
 *------------------------------------------------------------------------
 */
int inGetCPACTimeGap(CPAC_REC* srCPAC) {
    //  CPAC_REC srCPAC;

    //  vdLoadCPACParams(&srCPAC);
    return(srCPAC->inTimeGap);
}


/***************************************************************************************

    This function is for PFR Autosettlement feature.

***************************************************************************************/

int inCPACSetAutoHandle(TRANSACTION_OBJECT* pobTran) {
    inGlobalAutoHandle = 1;

    return(VS_SUCCESS);
}


int inResetDemoBatch(TRANSACTION_OBJECT* pobTran) {
    long lnBatchNum;
    int inBatchNumSize;

    /** /pdebug(("--inResetBatch--"));*/

    /* Increment batch num & save value in BDT after settle
     * Reset the mustsettle flag, & save value in HDT
     * in case the batch is cleared after a failed settlement.
     * but only if you are not in demo mode
     */
    if (fGetDemoMode()) {
        lnBatchNum = lnGetBatchNum();
        inBatchNumSize = inGetBatchNumSize();
        if (++lnBatchNum > lnMaxValue(inBatchNumSize))
            lnBatchNum = 1L;
        vdSetBatchNum(lnBatchNum);
        vdMustSettleHostFlags(VS_FALSE);
    }

    if (inSaveMHTRec(inGetBatchIndex()) != VS_SUCCESS)   /* Disk write */ {
        vdDisplayMessageFromFile(lnGGErrorMessage(), ERROR_MSG);
        return(VS_ERR);
    }

    return(VS_SUCCESS);
}


/* Saritha_b1................Start...Fix for Batch Upload for Processing Code */
#ifdef PROC_CODE_CHNG

void vdGetCPACPCChng(BATCH_REC* psrBRec,unsigned char* pszData) {
    unsigned char   szProcCode[PROC_CODE_SIZE + 1];

    memset(szProcCode, 0, PROC_CODE_SIZE);
    if (inGetBatchFieldData(psrBRec, CPAC_PROC_CODE, szProcCode, PROC_CODE_SIZE) != VS_ERR) {
        memcpy(pszData, szProcCode, PROC_CODE_SIZE);
        pszData[0] = pszData[0] & 0xF0;
        pszData[2] = 0x00;              // CPAC_UNBKL added CPAC_?

    }
}


void vdCPACPCChngBatRec2GDS(BATCH_REC* psrBRec) {
    vdGetCPACPCChng(psrBRec, srISO.pszField03);
}

#endif  /* PROC_CODE_CHNG*/

/* Saritha_b1................End...Fix for Batch Upload for Processing Code */
